// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// j [author] rhyme_lph
// W [email]  rhymelph@gmail.com
// S [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/address_entity.dart';
import 'package:finance_app/src/entities/business_contact_entity.dart';
import 'package:finance_app/src/entities/country_entity.dart';
import 'package:finance_app/src/http_service/http_common_service.dart';
import 'package:finance_app/src/http_service/http_contact_service.dart';
import 'package:finance_app/src/provider/dashboard/contact/all_contacts_provider.dart';
import 'package:finance_app/src/provider/dashboard/contact/business_contact_detail_provider.dart';
import 'package:finance_app/src/provider/dashboard/contact/main_business_contact_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/address_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/country_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';

class BusinessContactProfileProvider extends BaseProvider {
  FocusNode nameFocusNode = FocusNode();
  TextEditingController nameController = TextEditingController();

  TextEditingController phoneNumberController = TextEditingController();
  FocusNode phoneNumberFocusNode = FocusNode();

  String countryCode = '+65';

  TextEditingController emailController = TextEditingController();
  FocusNode emailFocusNode = FocusNode();

  TextEditingController websiteController = TextEditingController();
  FocusNode websiteFocusNode = FocusNode();

  bool isClient = false;

  CountryEntity country;

  String address;

  TextEditingController cityController = TextEditingController();
  FocusNode cityFocusNode = FocusNode();

  TextEditingController unitNoController = TextEditingController();
  FocusNode unitNoFocusNode = FocusNode();

  TextEditingController postalCodeController = TextEditingController();
  FocusNode postalCodeFocusNode = FocusNode();

  bool isEdit;

  List<String> menuList = [
    'Edit',
    'Delete',
  ];

  bool isSupport = false;

  bool hasBillingAddress = false;

  @override
  void dispose() {
    super.dispose();
    nameFocusNode.dispose();
    nameController.dispose();
    phoneNumberController.dispose();
    phoneNumberFocusNode.dispose();
    emailController.dispose();
    emailFocusNode.dispose();
    websiteController.dispose();
    websiteFocusNode.dispose();
    cityController.dispose();
    cityFocusNode.dispose();
    unitNoController.dispose();
    unitNoFocusNode.dispose();
    postalCodeController.dispose();
    postalCodeFocusNode.dispose();
  }

  @override
  Future get dataFuture => null;

  void unFocus() {
    postalCodeFocusNode.unfocus();
    unitNoFocusNode.unfocus();
    websiteFocusNode.unfocus();
    emailFocusNode.unfocus();
  }

  void updateCountryCode(value) {
    countryCode = value;
    update();
  }

  void onSelectCountry() {
    obtainContext?.call((context) async {
      final _country = await showCountryBottomSheet(
        context,
        country,
      );
      if (_country != null) {
        country = _country;
        update();
      }
    });
  }

  void onSelectAddress() {
    unFocus();
    obtainContext?.call((context) async {
      AddressEntity entity = await showAddressBottomSheet(context, null,
          (String searchData) async {
        List<AddressEntity> addressList;
        await post(HttpCommonService.searchAddress(searchData),
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          addressList = getEntityFromResult<List<AddressEntity>>(result);
        });
        if (addressList == null) {
          addressList = [];
        }
        return addressList;
      });
      if (entity != null) {
        address = entity.address;
        postalCodeController.text = entity.code;
        update();
      }
    });
  }

  int id;

  void initProfile(BusinessContactEntity data) {
    if (data == null) return;
    isEdit = false;
    id = data.id;
    nameController.text = data.name;
    phoneNumberController.text = data.phoneNumber;
    countryCode = data.countryCode;
    emailController.text = data.email;
    websiteController.text = data.website;
    isClient = data.isClient == 1;
    if (data.addressCountry != null) {
      country = Config.settingData.country
          .firstWhere((element) => element.key == data.addressCountry,
              orElse: () => CountryEntity()
                ..name = data.addressCountry
                ..key = data.addressCountry);
    }
    address = data.addressLine1;
    unitNoController.text = data.addressUnit;
    postalCodeController.text = data.addressPostalCode;
    isSupport = data.isSupplier == 1;
    hasBillingAddress = data.enableAddress == 1;
    cityController.text = data.addressCity;
  }

  void onSave() async {
    unFocus();
    if (nameController.text.length == 0) {
      showToast(S.current.please_enter_business_name);
      return;
    }

    if (phoneNumberController.text.length == 0) {
      showToast(S.current.please_enter_phone_number);
      return;
    }

    if (isClient == false && isSupport == false) {
      showToast(S.current.please_select_client_and_or_supplier);
      return;
    }

    BusinessContactEntity entity;

    if (isEdit == true) {
      await post(
          HttpContactService.updateContact(
            id,
            name: nameController.text,
            a: null,
            b: null,
            email: emailController.text,
            website: websiteController.text,
            is_taxable: 1,
            enable_address: hasBillingAddress ? 1 : 0,
            address_country: country?.key,
            address_city: cityController.text,
            address_postal_code: postalCodeController.text,
            address_line_1: address,
            address_line_2: address,
            address_unit: unitNoController.text,
            is_favorite: 0,
            is_client: isClient ? 1 : 0,
            is_supplier: isSupport ? 1 : 0,
            country_code: countryCode,
            phone_number: phoneNumberController.text,
          ),
          autoHandler: AutoHandler.Toast,
          loadingTip: S.current.loading, onSuccess: (result) {
        entity = getEntityFromResult<BusinessContactEntity>(result);
      });
    } else {
      await post(
          HttpContactService.createContact(
            name: nameController.text,
            a: null,
            b: null,
            email: emailController.text,
            website: websiteController.text,
            is_taxable: 1,
            enable_address: hasBillingAddress ? 1 : 0,
            address_country: country?.key,
            address_city: cityController.text,
            address_postal_code: postalCodeController.text,
            address_line_1: address,
            address_line_2: address,
            address_unit: unitNoController.text,
            is_favorite: 0,
            is_client: isClient ? 1 : 0,
            is_supplier: isSupport ? 1 : 0,
            country_code: countryCode,
            phone_number: phoneNumberController.text,
          ),
          autoHandler: AutoHandler.Toast,
          loadingTip: S.current.loading, onSuccess: (result) {
        entity = getEntityFromResult<BusinessContactEntity>(result);
      });
    }
    if (entity != null) {
      final provider = Providers.get<MainBusinessContactProvider>(
          RouterGenProviders.mainBusinessContactPage, null);
      if (provider != null) {
        provider.updateContact(entity);
      }
      final allProvider = Providers.get<AllContactsProvider>(
          RouterGenProviders.allContactsPage, null);
      if (allProvider != null) {
        allProvider.updateContact(entity);
      }
      final detailProvider = Providers.get<BusinessContactDetailProvider>(
          RouterGenProviders.businessContactDetailPage, null);
      if (detailProvider != null) {
        detailProvider.updateContact(entity);
      }
      obtainContext?.call((context) {
        Navigator.of(context).pop(entity);
      });
    }
  }

  void onSelectMenu(String value) {
    switch (menuList.indexOf(value)) {
      case 0:
        isEdit = !isEdit;
        update();
        break;
      case 1:
        onDelete();
        break;
    }
  }

  void onDelete() {
    obtainContext?.call((context) async {
      bool isSuccess = await showDeleteContactInfoBottomSheet(context);
      if (isSuccess == true) {
        isSuccess = false;
        await post(HttpContactService.deleteContact(id),
            loadingTip: S.current.loading,
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          isSuccess = true;
        });
        if (isSuccess) {
          await showContactSuccessBottomSheet(context);
          final provider = Providers.get<MainBusinessContactProvider>(
              RouterGenProviders.mainBusinessContactPage, null);
          if (provider != null) {
            provider.onDeleteContact(id);
          }
          final allProvider = Providers.get<AllContactsProvider>(
              RouterGenProviders.allContactsPage, null);
          if (allProvider != null) {
            allProvider.onDeleteContact(id);
          }
          Navigator.of(context).pop();
        }
      }
    });
  }

  void onSelectClient() {
    isClient = !isClient;
    update();
  }

  void onSelectSupport() {
    isSupport = !isSupport;
    update();
  }

  void onChangeBillAddress() {
    hasBillingAddress = !hasBillingAddress;
    update();
  }
}
